<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>websocket</title>
		<script src="./js/jquery-3.4.1.js" type="text/javascript" charset="UTF-8"></script>
	</head>
	<script>
		$(function(){
			var ws = new WebSocket("ws://127.0.0.1:8888");
			var heartTime;
			if(window.WebSocket){
				
				// 连接服务器
				ws.onopen = function(){
					debugger
					var html = "<span style='color:green'>连接服务器成功</span></br>";
					$("#toke").append(html);
                    // 连接成功后发送心跳
					sendHeart();
				}
				
				// 断开服务器
				ws.onclose = function(e){
					clearInterval(heartTime);
					var html = "<span style='color:red'>客户端断开连接</span></br>"
					$("#toke").append(html);
					
				}
				
				// 服务器发生异常
				ws.onerror = function(){
					var html = "<span style='color:red'>服务器异常</span></br>"
					$("#toke").append(html);
				}
				
				ws.onmessage = function(data){
                    // 判断服务端返回的值是否为心跳返回值
					if(data.data == "ws-heart"){
						return;
					}
					var html = "<span>服务器:"+ data.data +"</span></br>"
					$("#toke").append(html);
				}
			} else{
				alert("当前浏览器不支持WebSocket!");
			}
			
			$("#send").click(function(){
				var msg = $("#con").val();
				ws.send(msg);
				msg = "<span style='color:blue;display:block;text-align:right;margin-right:5px'>"+ msg +"</span></br>";
				var showMsg = $("#toke");
				showMsg.append(msg);
				$("#con").val("");
			});
			
			function sendHeart(){
				heartTime = setInterval(function(){
					ws.send("ws-heart");
				},5000);
			}
		})
	</script>
	<body>
		<div id="toke" style="width: 400px; height: 300px;border: 1px solid #f00;">
			
		</div>
		<input type="text" name="con" id="con" width="100px" />
		<button id="send">发送</button>
	</body>
</html>